<script setup lang="ts">
import { Plus } from 'lucide-vue-next';
import { Button } from '@/components/ui/button';
import DepartmentTreeNode from './DepartmentTreeNode.vue';
import DepartmentForm from './DepartmentForm.vue';
import { deleteDepartment } from '@/api/endpoints/system/department';
import type { DepartmentWithChildren } from '@/api/endpoints/system/department';

interface Props {
  departments: DepartmentWithChildren[];
  selectedDepartment: DepartmentWithChildren | null;
}

const props = defineProps<Props>();
const emit = defineEmits<{
  (e: 'update'): void;
  (e: 'select', department: DepartmentWithChildren): void;
}>();

const expandedNodes = ref<Set<string>>(new Set());
const showForm = ref(false);
const formMode = ref<'create' | 'edit'>('create');
const currentDepartment = ref<DepartmentWithChildren | null>(null);
const parentDepartment = ref<DepartmentWithChildren | null>(null);

// 递归获取所有部门ID（包括子部门）
function getAllDepartmentIds(departments: DepartmentWithChildren[]): string[] {
  const ids: string[] = [];
  departments.forEach(dept => {
    if (dept.id) {
      ids.push(dept.id);
    }
    if (dept.children && dept.children.length > 0) {
      ids.push(...getAllDepartmentIds(dept.children));
    }
  });
  return ids;
}

// 初始化展开状态 - 将所有部门都展开
function initializeExpandedState() {
  const allIds = getAllDepartmentIds(props.departments);
  expandedNodes.value = new Set(allIds);
}

// 监听部门数据变化，自动展开所有节点
watch(() => props.departments, () => {
  initializeExpandedState();
}, { immediate: true, deep: true });

// 选择部门
function handleSelect(department: DepartmentWithChildren) {
  emit('select', department);
}

// 创建部门
function handleCreate(parentDept?: DepartmentWithChildren) {
  formMode.value = 'create';
  parentDepartment.value = parentDept || null;
  currentDepartment.value = null;
  showForm.value = true;
}

// 编辑部门
function handleEdit(department: DepartmentWithChildren) {
  formMode.value = 'edit';
  currentDepartment.value = department;
  parentDepartment.value = null;
  showForm.value = true;
}

// 删除部门
async function handleDelete(department: DepartmentWithChildren) {
  await deleteDepartment(department.id);
  emit('update');
}

// 切换展开状态
function handleToggle(departmentId: string, expanded: boolean) {
  if (expanded) {
    expandedNodes.value.add(departmentId);
  } else {
    expandedNodes.value.delete(departmentId);
  }
}

// 表单成功回调
function handleFormSuccess() {
  showForm.value = false;
  emit('update');
}

// 表单关闭回调
function handleFormClose() {
  showForm.value = false;
}
</script>

<template>
  <div class="h-full flex flex-col">
    <div class="p-4 border-b border-border">
      <h2 class="text-lg font-semibold">
        部门管理
      </h2>
    </div>
    <!-- 工具栏 -->
    <div class="p-4">
      <Button
        size="sm"
        class="w-full"
        @click="handleCreate()"
      >
        <Plus class="w-4 h-4 mr-2" />
        新建部门
      </Button>
    </div>

    <!-- 部门树 -->
    <div class="flex-1 overflow-y-auto">
      <div class="w-full">
        <DepartmentTreeNode
          v-for="department of departments"
          :key="department.id"
          :department="department"
          :is-selected="selectedDepartment?.id === department.id"
          :is-expanded="expandedNodes.has(department.id)"
          @select="handleSelect"
          @create="handleCreate"
          @edit="handleEdit"
          @delete="handleDelete"
          @toggle="handleToggle"
        />
      </div>
    </div>

    <DepartmentForm
      :open="showForm"
      :mode="formMode"
      :department="currentDepartment"
      :parent-department="parentDepartment"
      @close="handleFormClose"
      @success="handleFormSuccess"
    />
  </div>
</template>
